package com.nanrui.mutualinductor.ui.page;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.batman.baselibrary.Constant;
import com.batman.baselibrary.RouterConstants;
import com.batman.baselibrary.utils.ActivityUtils;
import com.batman.baselibrary.utils.TipDialogUtils;
import com.batman.baselibrary.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.nanrui.mutualinductor.BluetoothInfo;
import com.nanrui.mutualinductor.R;
import com.nanrui.mutualinductor.data.DKPowerData;
import com.nanrui.mutualinductor.data.Objects;
import com.network.utils.LogUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ui.util.UIStatusBarHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import timber.log.Timber;

@Route(path = RouterConstants.MAIN_COMPONENT_MAIN_PATH)
public class MainActivity extends DKActivity {


    @BindView(R.id.tv_main_name)
    TextView mTvMainName;
    @BindView(R.id.tv_main_address)
    TextView mTvMainAddress;
    @BindView(R.id.tv_main_status)
    TextView mTvMainStatus;
    @BindView(R.id.list_view)
    RecyclerView mListView;
    @BindView(R.id.ll_device)
    LinearLayout llDevice;

    @BindView(R.id.ll_device_list)
    LinearLayout mLLDeviceList;

    @BindView(R.id.pb_list)
    ProgressBar mProgressBar;

    @BindView(R.id.tv_list_status)
    TextView mTvListStatus;

    private BluetoothDeviceAdapter bluetoothDeviceAdapter;

    private List<BluetoothDevice> bluetoothDevices;

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initViews() {
        UIStatusBarHelper.translucent(this);
    }

    @Override
    public void loadData(Bundle savedInstanceState) {


        bluetoothDevices = new ArrayList<>();
        this.bluetoothDeviceAdapter = new BluetoothDeviceAdapter(bluetoothDevices);
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mListView.setAdapter(this.bluetoothDeviceAdapter);
        bluetoothDeviceAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BluetoothDevice bluetoothDevice = (BluetoothDevice) bluetoothDeviceAdapter.getItem(position);
                switch (bluetoothDevice.getBondState()) {
                    default:
                        break;
                    case 12:

                        cancelBluetoothDiscovery();
                        connectBluetooth(bluetoothDevice);
                        break;
                    case 11:
                        break;
                    case 10:
                        bluetoothDevice.createBond();
                }
            }
        });
    }

    public void dismissDialog() {
        TipDialogUtils.dismissProgressDialog();
    }

    @OnClick({R.id.ll_ct_check, R.id.ll_pt_test, R.id.ll_data, R.id.ll_device})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_ct_check:
                if (!Constant.isDeug) {
                    if (getBluetoothInfo() == null || getBluetoothInfo().getBluetoothDevice() == null ||
                            getBluetoothInfo().getConnectStatus() != 2) {
                        ToastUtils.showLong("未连接设备");
                        return;
                    }
                }

                ActivityUtils.openActivity(mContext, CTCheckActivity.class);
                break;
            case R.id.ll_pt_test:
                if (!Constant.isDeug) {
                    if (getBluetoothInfo() == null || getBluetoothInfo().getBluetoothDevice() == null ||
                            getBluetoothInfo().getConnectStatus() != 2) {
                        ToastUtils.showLong("未连接设备");
                        return;
                    }
                }
                ActivityUtils.openActivity(mContext, PTCheckActivity.class);
//                ActivityUtils.openActivity(mContext, BlueTestActivity.class);
                break;
            case R.id.ll_data:
                ActivityUtils.openActivity(mContext, DataProcessingActivity.class);
                break;


            case R.id.ll_device:

                RxPermissions rxPermissions = new RxPermissions(this);
                rxPermissions
                        .requestEachCombined(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                        .subscribe(permission -> { // will emit 1 Permission object
                            if (permission.granted) {
                                // All permissions are granted !
                                Timber.tag(TAG).d(permission.name + " permission.granted");
                                if (isBluetoothEnable()) {

                                    if (mLLDeviceList.getVisibility() == View.GONE) {
                                        mLLDeviceList.setVisibility(View.VISIBLE);
                                        startBluetoothDiscovery();
                                    } else {
                                        mLLDeviceList.setVisibility(View.GONE);
                                        cancelBluetoothDiscovery();
                                        bluetoothDeviceAdapter.clearAll();
                                    }

                                } else {
                                    //蓝牙权限被禁止，请在权限管理中打开

                                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                    startActivityForResult(enableBtIntent, 888);
                                }
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // At least one denied permission without ask never again
                                Timber.tag(TAG).d(permission.name + " permission.shouldShowRequestPermissionRationale");
                            } else {
                                // At least one denied permission with ask never again
                                // Need to go to the settings
                                Timber.tag(TAG).d(permission.name + " permission.denied");
                            }
                        });


                break;
        }
    }

    @Override
    protected void serviceConnected() {
        super.serviceConnected();
        //连接上一次的连接的蓝牙
        connectBluetooth(null);
    }

    @Override
    public void onBondStateChanged(BluetoothDevice paramBluetoothDevice, int paramInt1, int paramInt2)
            throws RemoteException {
        LogUtils.d(TAG, "设备信息有变化");
        this.bluetoothDeviceAdapter.upsertItem(paramBluetoothDevice);
    }

    @Override
    public void onConnectError(BluetoothInfo paramBluetoothInfo) {
        setBluetoothDevice(paramBluetoothInfo.getBluetoothDevice());
        setConnectStatus(paramBluetoothInfo.getConnectStatus());
    }


    @Override
    public void onPreConnect(BluetoothInfo paramBluetoothInfo) throws RemoteException {
        super.onPreConnect(paramBluetoothInfo);
        setBluetoothDevice(paramBluetoothInfo.getBluetoothDevice());
        setConnectStatus((byte) 1);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TipDialogUtils.showProgressDialog(mContext, "", true, new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {

                    }
                });
            }
        });

    }

    @Override
    public void onConnected(BluetoothInfo paramBluetoothInfo)
            throws RemoteException {
        switch (paramBluetoothInfo.getBluetoothDevice().getBondState()) {
            default:
                break;
            case 12:
                LogUtils.d(TAG, "设备连起来了");

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        mLLDeviceList.setVisibility(View.GONE);
                        setBluetoothDevice(paramBluetoothInfo.getBluetoothDevice());
                        setConnectStatus(paramBluetoothInfo.getConnectStatus());
                    }
                });
                DKPowerData.loadSupportedCapabilities((short) 66);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        bluetoothDeviceAdapter.clearAll();
//                        sendPacket(new Packet_11(), new PacketCallback() {
//                            public void packetReceived(final Packet_11 paramAnonymous2Packet_11) {
//                                DKMessageCode localDKMessageCode = paramAnonymous2Packet_11.getMessageCode();
//                                if (localDKMessageCode != null) {
//                                    paramAnonymous2Packet_11 = MainActivity.LOG;
//                                    StringBuilder localStringBuilder = new StringBuilder();
//                                    localStringBuilder.append("������������. ���������: ");
//                                    localStringBuilder.append(localDKMessageCode.getCode());
//                                    paramAnonymous2Packet_11.error(localStringBuilder.toString());
//                                    return;
//                                }
//                                runOnUiThread(new Runnable() {
//                                    public void run() {
//                                        TextView localTextView = hardwareVer;
//                                        StringBuilder localStringBuilder = new StringBuilder();
//                                        localStringBuilder.append(String.format(Locale.getDefault(), "%02d", new Object[]{Short.valueOf(paramAnonymous2Packet_11.getsVerA())}));
//                                        localStringBuilder.append(".");
//                                        localStringBuilder.append(String.format(Locale.getDefault(), "%02d", new Object[]{Short.valueOf(paramAnonymous2Packet_11.getsVerB())}));
//                                        localStringBuilder.append(".");
//                                        localStringBuilder.append(String.format(Locale.getDefault(), "%02d", new Object[]{Short.valueOf(paramAnonymous2Packet_11.getsVerC())}));
//                                        localTextView.setText(localStringBuilder.toString());
//                                    }
//                                });
//                            }
//                        });
//                    }
//                });
                break;
        }
    }

    @Override
    public void onDisconnected(BluetoothInfo paramBluetoothInfo)
            throws RemoteException {

        setBluetoothDevice(paramBluetoothInfo.getBluetoothDevice());
        setConnectStatus((byte) 0);
        if (paramBluetoothInfo.getNextBluetoothDevice() == null) {
            ToastUtils.showLong("蓝牙连接已断开");
        }
//        this.hardwareVer.setText("--.--.--");
    }

    @Override
    public void onDiscoveryFinished()
            throws RemoteException {
        LogUtils.d(TAG, "搜索附近的设备结束");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvListStatus.setText("搜索结束");
                mProgressBar.setVisibility(View.GONE);
            }
        });

    }

    @Override
    public void onDiscoveryStarted()
            throws RemoteException {
        LogUtils.d(TAG, "开始搜索附近的设备");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvListStatus.setText("开始搜索");
                mProgressBar.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onFound(BluetoothDevice paramBluetoothDevice)
            throws RemoteException {
        LogUtils.d(TAG, "发现设备...");
        this.bluetoothDeviceAdapter.upsertItem(paramBluetoothDevice);
    }

    class BluetoothDeviceAdapter extends BaseQuickAdapter<BluetoothDevice, BaseViewHolder> {

        public BluetoothDeviceAdapter(@Nullable List<BluetoothDevice> data) {
            super(R.layout.item_device_list, data);
        }


        @Override
        protected void convert(BaseViewHolder helper, BluetoothDevice item) {

            if (TextUtils.isEmpty(item.getName())) {
                helper.setText(R.id.name, "");
            } else {
                helper.setText(R.id.name, item.getName().replaceFirst("^DK-?45D1\\+[^\\d]*", ""));
            }
            helper.setText(R.id.address, item.getAddress());

            switch (item.getBondState()) {
                default:
                    break;
                case 12:
                    helper.setText(R.id.status, "已配对");
                    break;
                case 11:
                    helper.setText(R.id.status, "正在配对");
                    break;
                case 10:
                    helper.setText(R.id.status, "未配对");
            }


        }


        public void upsertItem(BluetoothDevice paramBluetoothDevice) {
            LogUtils.d(TAG, paramBluetoothDevice.getAddress());
            if (bluetoothDevices.contains(paramBluetoothDevice)) {
                bluetoothDevices.set(getData().indexOf(paramBluetoothDevice), paramBluetoothDevice);
            } else {
                bluetoothDevices.add(paramBluetoothDevice);
            }
            notifyDataSetChanged();
        }

        public void clearAll() {
            bluetoothDevices.clear();
            notifyDataSetChanged();
        }
    }

    /**
     * 显示状态
     *
     * @return
     */

    private BluetoothDevice bluetoothDevice;
    private byte connectStatus;

    public String getConnectStatusMessage() {
        switch (this.connectStatus) {
            default:
                return "等待连接";
            case 4:
                return "正在断开";
            case 3:
                return "连接出错";
            case 2:
                return "已连接";
            case 1:
                return "正在连接";

        }
    }

    public boolean getIsConnected() {
        boolean bool;
        if (this.connectStatus == 2) {
            bool = true;
        } else {
            bool = false;
        }
        return bool;
    }

    public void setBluetoothDevice(BluetoothDevice paramBluetoothDevice) {
        if (Objects.notEquals(this.bluetoothDevice, paramBluetoothDevice)) {
            this.bluetoothDevice = paramBluetoothDevice;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (bluetoothDevice != null) {
                    mTvMainName.setText(bluetoothDevice.getName());
                    mTvMainAddress.setText(bluetoothDevice.getAddress());
                }
            }
        });

    }

    public void setConnectStatus(byte paramByte) {
        if (this.connectStatus != paramByte) {
            this.connectStatus = ((byte) paramByte);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvMainStatus.setText(getConnectStatusMessage());
                dismissDialog();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 888 && resultCode == RESULT_OK) {
            if (mLLDeviceList.getVisibility() == View.GONE) {
                mLLDeviceList.setVisibility(View.VISIBLE);
                startBluetoothDiscovery();
            } else {
                mLLDeviceList.setVisibility(View.GONE);
                cancelBluetoothDiscovery();
                bluetoothDeviceAdapter.clearAll();
            }
        }
    }
}
